<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>从零开始搭建一个主流项目框架（五）—GreenDao的增删改查 | 海晨忆的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  
  
  <meta name="description" content="&amp;emsp;&amp;emsp;上一篇我们讲了GreenDao的数据库的依赖和创建，这一篇，我们来讲常用的增删改查四种方法。我们操作数据库都是Dao层，不同的表，有不懂的Dao层对象。我们上一篇的数据库接口的实现类里面，我们定义了UserDao，我们这一篇讲的就是操作我们昨天创建的user表。">
<meta property="og:type" content="article">
<meta property="og:title" content="从零开始搭建一个主流项目框架（五）—GreenDao的增删改查">
<meta property="og:url" content="https://haichenyi.com/2018/02/24/从零开始搭建一个主流项目框架（五）—GreenDao的增删改查/index.html">
<meta property="og:site_name" content="海晨忆的博客">
<meta property="og:description" content="&amp;emsp;&amp;emsp;上一篇我们讲了GreenDao的数据库的依赖和创建，这一篇，我们来讲常用的增删改查四种方法。我们操作数据库都是Dao层，不同的表，有不懂的Dao层对象。我们上一篇的数据库接口的实现类里面，我们定义了UserDao，我们这一篇讲的就是操作我们昨天创建的user表。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://haichenyi.com/uploads/article/2018-02-24/增1.png">
<meta property="og:image" content="https://haichenyi.com/uploads/article/2018-02-24/增2.png">
<meta property="og:image" content="https://haichenyi.com/uploads/article/2018-02-24/增3.png">
<meta property="og:image" content="https://haichenyi.com/uploads/article/2018-02-24/增4.png">
<meta property="og:image" content="https://haichenyi.com/uploads/article/2018-02-24/增5.png">
<meta property="og:updated_time" content="2019-09-18T09:09:54.575Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="从零开始搭建一个主流项目框架（五）—GreenDao的增删改查">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;上一篇我们讲了GreenDao的数据库的依赖和创建，这一篇，我们来讲常用的增删改查四种方法。我们操作数据库都是Dao层，不同的表，有不懂的Dao层对象。我们上一篇的数据库接口的实现类里面，我们定义了UserDao，我们这一篇讲的就是操作我们昨天创建的user表。">
<meta name="twitter:image" content="https://haichenyi.com/uploads/article/2018-02-24/增1.png">
  
    <link rel="alternate" href="/atom.xml" title="海晨忆的博客" type="application/atom+xml">
  
  
    <link rel="icon" href="/uploads/artistic_image/head.jpg">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/css/highlight.css">
  <script>
  let antiquityStorage = window.sessionStorage.getItem('antiquitySessionStorage');
  if (antiquityStorage == '' || antiquityStorage == null) {
    var antiquityLoader = '<div id="loaderbox"><div class="loader"><div class="load-roll"><div class="load-top"></div><div class="load-right"></div><div class="load-bottom"></div></div></div></div>';
    document.write(antiquityLoader);
    document.body.style.overflow = 'hidden'
  }
  </script>
</head>

<body>
  <div id="fullpage" class="mobile-nav-right">
    
      <div id="wrapper" style="background-image: url(/uploads/artistic_image/bg.jpg)" title="背景图片来自网络">
    
    
      <header id="header">
  <div id="nav-toggle" class="nav-toggle"></div>
  <div class="head-box global-width">
    <nav class="nav-box nav-right">
      
        <a class="nav-item" href="/" title
        
        >首页</a>
      
        <a class="nav-item" href="/archives" title
        
        >归档</a>
      
        <a class="nav-item" href="/about" title
        
        >简历</a>
      
    </nav>
  </div>
</header>
      <div id="middlecontent" title class="global-width sidebar-left">
        <section id="main"><article id="post-从零开始搭建一个主流项目框架（五）—GreenDao的增删改查" class="article global-container article-type-post" itemscope itemprop="blogPost">
  
    <header class="article-header">
      
  
    <h1 class="article-title" itemprop="name">
      从零开始搭建一个主流项目框架（五）—GreenDao的增删改查
    </h1>
  

    </header>
  
  <div class="article-meta">
    <a href="/2018/02/24/从零开始搭建一个主流项目框架（五）—GreenDao的增删改查/" class="article-date">
  <time datetime="2018-02-24T13:17:55.000Z" itemprop="datePublished">2018-02-24</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/Android-框架/">Android -框架</a>
  </div>

    
  </div>
  
    <span id="busuanzi_container_page_pv">
      本文总阅读量<span id="busuanzi_value_page_pv"></span>次
    </span>
  

  <div class="article-inner">
    
    <div class="article-content article-content-cloud doorframe mac" itemprop="articleBody">
      
        <p>&emsp;&emsp;上一篇我们讲了GreenDao的数据库的依赖和创建，这一篇，我们来讲常用的增删改查四种方法。我们操作数据库都是Dao层，不同的表，有不懂的Dao层对象。我们上一篇的数据库接口的实现类里面，我们定义了UserDao，我们这一篇讲的就是操作我们昨天创建的user表。</p>
<a id="more"></a>
<p>&emsp;&emsp;在写下面几个方法之前，我还是先把MVP的用法先讲一遍吧，防止有人不知道，以增操作为例，另外三个就不再讲了：</p>
<ol>
<li><p>点击页面的增按钮，我们要调用P层的方法去做增操作。效果图如下：<br><img src="/uploads/article/2018-02-24/增1.png" alt="增1.png"></p>
</li>
<li><p>P层的方法从哪来呢？P层实现的接口来撒，所以，我们只用在接口定义对应的方法，在P层去实现，效果图如下：<br><img src="/uploads/article/2018-02-24/增2.png" alt="增2.png"></p>
</li>
<li><p>辣么，具体实现代码怎么写呢？既不记得，我们的装饰者模式，我们P层里面有一个DataHelper对象，通过它去调用对应的方法就可以了，效果图如下：<br><img src="/uploads/article/2018-02-24/增3.png" alt="增3.png"></p>
</li>
<li><p>接下来，datahelper的方法又是从哪里来呢？我们的DataHelper是不是实现了SqlHelper接口，所以，直接在SqlHelper定义方法，在datahelper实现即可，效果图如下：<br><img src="/uploads/article/2018-02-24/增4.png" alt="增4.png"></p>
</li>
<li><p>最后，前面只是调用了，具体实现在哪里呢？我之前有没有讲过装饰者模式，一个接口，两个实现方法，对，没错，就是在SqlImpl方法里面实现，效果图如下：<br><img src="/uploads/article/2018-02-24/增5.png" alt="增5.png"></p>
</li>
</ol>
<p>&emsp;&emsp;通过以上5步，就完成我们的增操作。有同鞋就会问，那参数怎么传？我特么怎么知道需要传什么传输，你这个方法是干什么的，调用这个方法需要什么数据，你就丢在参数里面传过去，即可。</p>
<h3 id="增"><a href="#增" class="headerlink" title="增"></a>增</h3><h4 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">//插入单个对象</span><br><span class="line">userDao.insert(user);</span><br><span class="line"></span><br><span class="line">//插入一个list</span><br><span class="line">userDao.insertInTx(users);</span><br></pre></td></tr></table></figure></div>
<h4 id="调用"><a href="#调用" class="headerlink" title="调用"></a>调用</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">//basePresenter.onAdd(User(&quot;小红&quot;, 1, 165, &quot;50KG&quot;, 18))</span><br><span class="line">val dataList = mutableListOf&lt;User&gt;()</span><br><span class="line">dataList.add(User(&quot;小刚&quot;, 2, 175, &quot;60KG&quot;, 28))</span><br><span class="line">dataList.add(User(&quot;小东&quot;, 2, 185, &quot;65KG&quot;, 25))</span><br><span class="line">basePresenter.onAddList(dataList)</span><br></pre></td></tr></table></figure></div>
<p>效果图我就不贴出来了，如果，你的效果出不来，就肯定是你的代码写的有问题，我写这个博客都是边写代码，边写博客，我这边肯定是没问题的。</p>
<h3 id="查"><a href="#查" class="headerlink" title="查"></a>查</h3><h4 id="方法-1"><a href="#方法-1" class="headerlink" title="方法"></a>方法</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">//查询单个对象</span><br><span class="line">userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().unique();</span><br><span class="line">//查询一个list</span><br><span class="line">userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().list();</span><br></pre></td></tr></table></figure></div>
<h4 id="调用-1"><a href="#调用-1" class="headerlink" title="调用"></a>调用</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">val user = basePresenter.onSelect(&quot;小红&quot;)</span><br><span class="line">println(user.name)</span><br><span class="line">val users = basePresenter.onSelectList(&quot;小东&quot;)</span><br><span class="line"> users.forEach &#123;</span><br><span class="line">     println(it.name)</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;这里，我需要做一点说明，那就是手动能力强的宝宝，看见有两个查询方法，一个查询一个对象，一个查询list，这两个方法没问题，查询肯定是查询的一个，list里面也是只有一个对象，就有宝宝想着多插入几条数据，这个时候，项目就可能崩掉，因为，你插入的名字是相同的，我们这里名字是作为主键，表里面主键是不能相同的，所以就崩掉了，所以，你就得改表结构，正好测试我们之前说的版本更新问题，我这里亲测可用，数据也不会丢失。步骤如下：</p>
<ol>
<li>修改数据库版本，把1改成2</li>
<li>User bean里面增加一个字段id Long类型，递增即可，clean，build项目</li>
<li>在你的Activity里面会报错，因为，你User的构造方法里面新增了一个参数，辣么这里你用的时候参数个数都不对，肯定报错，你把id字段对应的参数传null即可，他自己递增。这里也只有Long类型可以传null</li>
<li>重新运行项目，没有问题</li>
</ol>
<h3 id="删"><a href="#删" class="headerlink" title="删"></a>删</h3><h4 id="方法-2"><a href="#方法-2" class="headerlink" title="方法"></a>方法</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/*//通过主键删除一个对象，删除满足条件的第一个对象</span><br><span class="line">    User user1 = userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().unique();</span><br><span class="line">    //一定要记得做非空判断</span><br><span class="line">    if (user1 != null) &#123;</span><br><span class="line">      userDao.deleteByKey(user1.getId());</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">      ToastUtils.Companion.showTipMsg(&quot;为查询到相关数据&quot;);</span><br><span class="line">    &#125;*/</span><br><span class="line"></span><br><span class="line">    //通过主键删除一个满足条件的List</span><br><span class="line">    List&lt;User&gt; list = userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().list();</span><br><span class="line">    if (list.size() &gt; 0) &#123;</span><br><span class="line">      List&lt;Long&gt; keys = new ArrayList&lt;&gt;();</span><br><span class="line">      for (User user : list) &#123;</span><br><span class="line">        keys.add(user.getId());</span><br><span class="line">      &#125;</span><br><span class="line">      userDao.deleteByKeyInTx(keys);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">      ToastUtils.Companion.showTipMsg(&quot;为查询到相关数据&quot;);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="调用-2"><a href="#调用-2" class="headerlink" title="调用"></a>调用</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//basePresenter.onDelete(&quot;小红&quot;)</span><br><span class="line">basePresenter.onDelete(&quot;小东&quot;)</span><br></pre></td></tr></table></figure></div>
<h3 id="改"><a href="#改" class="headerlink" title="改"></a>改</h3><h4 id="方法-3"><a href="#方法-3" class="headerlink" title="方法"></a>方法</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">List&lt;User&gt; list = userDao.queryBuilder().where(UserDao.Properties.Name.eq(oldName)).build().list();</span><br><span class="line">    if (list.size() &gt; 0) &#123;</span><br><span class="line">      for (User user : list) &#123;</span><br><span class="line">        user.setName(newName);</span><br><span class="line">      &#125;</span><br><span class="line">//      userDao.update(user1);</span><br><span class="line">      userDao.updateInTx(list);</span><br><span class="line">      ToastUtils.Companion.showTipMsg(&quot;修改成功&quot;);</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">      ToastUtils.Companion.showTipMsg(&quot;未查询到相关数据&quot;);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<h4 id="调用-3"><a href="#调用-3" class="headerlink" title="调用"></a>调用</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">basePresenter.onUpdate(&quot;小刚&quot;, &quot;小贝&quot;)</span><br></pre></td></tr></table></figure></div>
<p>完了，数据库的简单的增删改查</p>
<p><a href="http://download.csdn.net/download/qq_27634797/10257729" target="_blank" rel="noopener">项目链接</a></p>

      
    </div>
    
      <footer class="article-footer">
        完
      </footer>
    
  </div>
  
    
<nav id="article-nav">
  <div class="article-nav-block">
    
      <a href="/2018/02/26/从零开始搭建一个主流项目框架（六）—Socket网络编程/" id="article-nav-newer" class="article-nav-link-wrap">
        <strong class="article-nav-caption"></strong>
        <div class="article-nav-title">
          
            从零开始搭建一个主流项目框架（六）——Socket网络编程
          
        </div>
      </a>
    
  </div>
  <div class="article-nav-block">
    
      <a href="/2018/02/24/从零开始搭建一个主流项目框架（四）—Kotlin-GreenDao3-2/" id="article-nav-older" class="article-nav-link-wrap">
        <div class="article-nav-title">从零开始搭建一个主流项目框架（四）—Kotlin+GreenDao3.2</div>
        <strong class="article-nav-caption"></strong>
      </a>
    
  </div>
</nav>

    
  
  
</article>
</section>
        <aside id="sidebar">
  
    <div class="widget-box">
  <div class="avatar-box avatar-item">
    <img class="avatar" src="/uploads/artistic_image/head.jpg" title="头像来自网络"></img>
    <h3 class="avatar-name">
      
        海晨忆
      
    </h3>
    <p class="avatar-slogan">
      先谋生，再谋爱。人间值得，未来可期。
    </p>
  </div>
</div>


  
    
  <div class="widget-box">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android-Socket/">Android -Socket</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-加密算法/">Android -加密算法</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-常用功能/">Android -常用功能</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-框架/">Android -框架</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-源码解析/">Android -源码解析</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-自定义view/">Android -自定义view</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-设计模式/">Android -设计模式</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/JAVA-并发/">JAVA -并发</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java-SpringBoot/">Java -SpringBoot</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tomcat/">Tomcat</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/kotlin/">kotlin</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-JDBC/">数据库 -JDBC</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-MySQL/">数据库 -MySQL</a></li></ul>
    </div>
  </div>


  
    

  
    
  
    
  <div class="widget-box">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">July 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/11/">November 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/10/">October 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/09/">September 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">August 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">July 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">June 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">October 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">May 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">March 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">February 2018</a></li></ul>
    </div>
  </div>

  
    
  <div class="widget-box">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/07/27/JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁/">JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁</a>
          </li>
        
          <li>
            <a href="/2021/07/19/JAVA—线程同步器AQS/">JAVA—线程同步器AQS</a>
          </li>
        
          <li>
            <a href="/2021/07/07/Android模拟点击/">Android模拟点击</a>
          </li>
        
          <li>
            <a href="/2019/11/27/SpringBoot系列-消息-RabbitMQ-（二十）/">SpringBoot系列-消息(RabbitMQ)（二十）</a>
          </li>
        
          <li>
            <a href="/2019/11/13/SpringBoot系列-Docker（十九）/">SpringBoot系列-Docker（十九）</a>
          </li>
        
      </ul>
    </div>
  </div>

  
      <div class="widget-box">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget">
      
        <a class="hrf" style="display: block;" href="https://github.com/haichenyi" title target='_blank'
        >Github</a>
      
        <a class="hrf" style="display: block;" href="https://www.jianshu.com/u/6077ee440c37" title target='_blank'
        >简书</a>
      
        <a class="hrf" style="display: block;" href="https://blog.csdn.net/qq_27634797" title target='_blank'
        >CSDN</a>
      
    </div>
  </div>

  
</aside>
      </div>
      <footer id="footer">
  <div class="foot-box footers global-width">
    &copy;2017-2021 海晨忆 &nbsp;&nbsp;
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">阁下是第<span id="busuanzi_value_site_pv"></span>个访客</span>
  </div>
</footer>
      <script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
if (!window.jQuery) {
var script = document.createElement('script');
script.src = "/js/jquery-2.0.3.min.js";
document.body.write(script);
}
</script>

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



    </div>
    <nav id="mobile-nav" class="mobile-nav-box">
  <div class="mobile-nav-img mobile-nav-top"></div>
  
    <a href="/" class="mobile-nav-link">首页</a>
  
    <a href="/archives" class="mobile-nav-link">归档</a>
  
    <a href="/about" class="mobile-nav-link">简历</a>
  
  <div class="mobile-nav-img  mobile-nav-bottom"></div>
</nav>    
  </div>
</body>
</html>